import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { FieldType } from './field-type.entity';

@Injectable()
export class FieldTypeService {
  constructor(
    @InjectRepository(FieldType)
    private readonly fieldTypeRepository: Repository<FieldType>,
  ) {}

  async findAll(): Promise<FieldType[]> {
    return this.fieldTypeRepository.find({
      where: { enabled: true },
      order: { sortOrder: 'ASC' }
    });
  }

  async findOne(id: number): Promise<FieldType> {
    const fieldType = await this.fieldTypeRepository.findOne({ where: { id } });
    if (!fieldType) {
      throw new NotFoundException(`FieldType with ID ${id} not found`);
    }
    return fieldType;
  }

  async create(fieldTypeData: Partial<FieldType>): Promise<FieldType> {
    const fieldType = this.fieldTypeRepository.create(fieldTypeData);
    return this.fieldTypeRepository.save(fieldType);
  }

  async update(id: number, fieldTypeData: Partial<FieldType>): Promise<FieldType> {
    await this.fieldTypeRepository.update(id, fieldTypeData);
    return this.findOne(id);
  }

  async remove(id: number): Promise<void> {
    const result = await this.fieldTypeRepository.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException(`FieldType with ID ${id} not found`);
    }
  }

  async initializeDefaultFields(): Promise<void> {
    const defaultFields = [
      {
        key: 'name',
        label: '姓名',
        type: 'text',
        required: true,
        sortOrder: 1
      },
      {
        key: 'phone',
        label: '联系电话',
        type: 'tel',
        required: true,
        sortOrder: 2
      },
      {
        key: 'company',
        label: '企业名称',
        type: 'text',
        required: false,
        sortOrder: 3
      },
      {
        key: 'personnel',
        label: '参加项目人员',
        type: 'text',
        required: false,
        sortOrder: 4
      },
      {
        key: 'region',
        label: '地区',
        type: 'text',
        required: false,
        sortOrder: 5
      },
      {
        key: 'industry',
        label: '行业',
        type: 'select',
        required: false,
        options: ['制造业', '服务业', '科技', '金融', '教育', '医疗', '建筑', '零售', '物流', '农业', '其他'],
        sortOrder: 6
      },
      {
        key: 'message',
        label: '留言内容',
        type: 'textarea',
        required: false,
        sortOrder: 7
      }
    ];

    for (const fieldData of defaultFields) {
      const existingField = await this.fieldTypeRepository.findOne({ where: { key: fieldData.key } });
      if (!existingField) {
        await this.create(fieldData);
      }
    }
  }
}